package com.lancer.cloud.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

/**
 * freemarker 工具类
 *
 * @author caijinbang
 * @date 2019-06-25 13:03
 */
public class FreeMarkerUtils extends FreeMarkerTemplateUtils {

    public static final String BOOLEAN_TEMPLATE = "<#if {0}>true<#else>false</#if>";

    /**
     * 字符串解析
     */
    @SuppressWarnings("deprecation")
    public static String renderString(String templateString, Map<String, ?> model) throws IOException, TemplateException {
        Template t = new Template("default", new StringReader(templateString),
            Configuration.getDefaultConfiguration());
        return processTemplateIntoString(t, model);
    }

    /**
     * 返回解析结果
     *
     * @param expression 表达式
     * @param params 填充参数
     */
    public static String paraseResult(String expression, Map<String, Object> params)
        throws IOException, TemplateException {
        expression = expression.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\{", "'")
            .replaceAll("\\}",
                "'").replaceAll(">=", " gte ").replaceAll("<=", " lte ").replaceAll(">", " gt ")
            .replaceAll("<", " lt" +
                " ").replaceAll("==", "=").replaceAll("=", "==").replaceAll("≠", "!=");
        String template = MessageFormat.format(FreeMarkerUtils.BOOLEAN_TEMPLATE, expression);
        return FreeMarkerUtils.render(template, params);
    }

    /**
     * freemarker的字符参数不能以字母开头，预处理
     */
    public static String render(String template, Map<String, Object> params)
        throws IOException, TemplateException {
        Iterator it = params.entrySet().iterator();
        Map<String, Object> replaceParams = new HashMap<>();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            String key = entry.getKey();
            if (key.matches("[0-9]+.*")) {
                //将key为数字开头的替换成字母开头
                String replaceKey = "A" + key;
                template = template.replaceAll(key, replaceKey);
                replaceParams.put(replaceKey, params.get(key));
            } else {
                replaceParams.put(key, params.get(key));
            }
        }
        return FreeMarkerUtils.renderString(template, replaceParams);
    }

}
